package com.gitee.wsl.jvm.autosave

import timber.log.Timber
import java.util.ServiceLoader


object SPIUtils {
    /**
     * 如果有多个实现，取第一个
     */
    fun <T> getSpiImpl(t: Class<T>): T? {
        try {
            val loader = ServiceLoader.load(t, SPIUtils::class.java.classLoader)
            val iter: Iterator<T> = loader.iterator()
            if (iter.hasNext()) {
                return iter.next()
            }
        } catch (e: Exception) {
           Timber.e(e)
        }
        return null
    }

    /**
     * 返回所有实现
     */
    fun <T> getSpiImpls(t: Class<T>): List<T> {
        val impls: MutableList<T> = ArrayList()
        try {
            val loader = ServiceLoader.load(t, SPIUtils::class.java.classLoader)
            val iter: Iterator<T> = loader.iterator()
            while (iter.hasNext()) {
                impls.add(iter.next())
            }
        } catch (e: Exception) {
            Timber.e(e)
        }
        return impls
    }

}